"""
文件上传。
"""
import os
from tornado import web


class FileUploadHandler(web.RequestHandler):
    """
    上传文件类。
    """
    path: str

    def initialize(self, path: str):
        """
        初始化。
        :param path: 存放文件的目录。
        """
        self.path = path

    async def post(self):
        """
        处理文件上传。
        """
        for file in self.request.files['file']:
            name = file['filename']
            body = file['body']
            with open(os.path.join(self.path, name), 'wb') as f:
                f.write(body)
        self.add_header('Access-Control-Allow-Origin', '*')

    async def options(self):
        """
        处理跨域。
        """
        self.add_header('Access-Control-Allow-Origin', '*')
